﻿using AutoMapper;
using MediatR;
using S.Y.Passport.Domain.溯源;
using S.Y.Passport.ErroeCode;
using S.Y.Passport.Infacet;
using S.Y.Passport.Write.API.Applications.Commands;
using S.Y.Passport.Write.API.Dtos;

namespace S.Y.Passport.Write.API.Applications.CommandHandler
{
    public class GetGoodsQueryCommandHandler : IRequestHandler<GetGoodsQueryCommand, SyResult<SyPaing<GoodsInfo>>>
    {
        private readonly IBaseRepo<GoodsInfo> goodsInfoRepo;
        private readonly IMapper mapper;

        public GetGoodsQueryCommandHandler(IBaseRepo<GoodsInfo> goodsInfoRepo, IMapper mapper)
        {
            this.goodsInfoRepo = goodsInfoRepo;
            this.mapper = mapper;
        }
        public Task<SyResult<SyPaing<GoodsInfo>>> Handle(GetGoodsQueryCommand request, CancellationToken cancellationToken)
        {
            SyResult<SyPaing<GoodsInfo>> result = new SyResult<SyPaing<GoodsInfo>>();

            result.Msg = SyCode.显示成功.ToString();
            result.Code = SyCode.显示成功;

            var lisy = goodsInfoRepo.GetAll().Where(x=>x.IsDeleted==false);

            var count = lisy.Count();
            var page = (int)Math.Ceiling(count * 1.0 / request.PageSize);
            var models = lisy.OrderByDescending(x => x.CreateTime).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageIndex);
            SyPaing<GoodsInfo> paging = new SyPaing<GoodsInfo>();
            paging.PageCount = page;
            paging.TotalCount = count;
            paging.Sylist = mapper.Map<List<GoodsInfo>>(models);

            result.Data = paging;

            return Task.FromResult(result);
        }
    }
}